package com.hertz.appr.http;

import java.net.URL;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.log4j.Logger;

public class HttpClientManager {

  private static Logger log = Logger.getLogger(HttpClientManager.class);

  private static MultiThreadedHttpConnectionManager httpClientManager = new MultiThreadedHttpConnectionManager();

  static {
    httpClientManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams params = httpClientManager.getParams();
    params.setStaleCheckingEnabled(true);
    params.setMaxTotalConnections(200);
    params.setDefaultMaxConnectionsPerHost(80);
    params.setConnectionTimeout(3000);
    params.setSoTimeout(3000);
  }

  private static HttpClient getHttpClient() {
    return new HttpClient(httpClientManager);
  }

  public static String get(String url) throws Exception {
    log.error("url=" + url);
    GetMethod method = null;
    try {
      HostConfiguration config = new HostConfiguration();
      URL photoBlogUrl = new URL(url);
      int port = photoBlogUrl.getPort() > 0 ? photoBlogUrl.getPort() : 80;
      config.setHost(photoBlogUrl.getHost(), port, photoBlogUrl.getProtocol());
      method = new GetMethod(url);
      getHttpClient().executeMethod(config, method);
      int statusCode = method.getStatusCode();
      if (statusCode != 200) {
        log.error("statusCode:" + statusCode + ". url:" + url);
        return null;
      }
      String redirectUrl = method.getResponseBodyAsString();
      return redirectUrl;

    } catch (Exception exp) {
      exp.printStackTrace();

    } finally {
      if (method != null) {
        method.releaseConnection();
      }
    }
    return null;
  }
}
